package com.stellar.wechat.core.common;

import com.stellar.wechat.core.common.exception.WxApiException;
import com.stellar.wechat.core.enums.WxErrorCode;
import org.apache.commons.codec.binary.Hex;
import org.springframework.http.HttpStatus;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.Map;
import java.util.TreeMap;


/**
 * @Author Jqcc
 * @Version 1.0
 * @Data 2025/3/30
 * @Description 签名工具类：提供生成签名和验证签名的功能
 */
public class SignatureUtil {
    public static String generateHmacSHA256(Map<String, String> params, String secret) {
        TreeMap<String, String> sortedParams = new TreeMap<>(params);
        StringBuilder sb = new StringBuilder();
        sortedParams.forEach((k, v) -> sb.append(k).append("=").append(v).append("&"));
        String paramStr = sb.substring(0, sb.length() - 1);

        try {
            Mac sha256 = Mac.getInstance("HmacSHA256");
            sha256.init(new SecretKeySpec(secret.getBytes(), "HmacSHA256"));
            return Hex.encodeHexString(sha256.doFinal(paramStr.getBytes()));
        } catch (Exception e) {
            throw new WxApiException(WxErrorCode.SIGNATURE_ERROR);
        }
    }

}